//
//  MYGCommunityRecommendController.swift
//  MYGrow
//
//  Created by lance on 2024/2/29.
//

import UIKit

class MYGCommunityRecommendController: MYGBaseController {
    // MARK: - Property
    var contents: [MYGCommunityRecommendCellModel] = []
    override var navigationBackgroundColor: UIColor {
        .clear
    }
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configUI()
       // configItem()
        loadData()
    }
    
    // MARK: - UI
    private func configUI() {
        self.title = "问问"
        view.backgroundColor = .white
        view.addSubviews([
            backgroundImageView,
            recommnedTitleLabel,
            recommentSubtitleLabel,
            recommentView,
            followButton
        ])
        
        backgroundImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        recommnedTitleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(14)
            make.height.equalTo(35)
        }
        
        recommentSubtitleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalTo(recommnedTitleLabel.snp.bottom).offset(4.5)
            make.height.equalTo(22.5)
        }
        
        followButton.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 189, height: 40))
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-25-bottomSafeheight)
        }
        
        recommentView.snp.makeConstraints { make in
            make.bottom.equalTo(followButton.snp.top).offset(20)
            make.left.right.equalToSuperview()
            make.top.equalTo(recommentSubtitleLabel.snp.bottom).offset(0)
        }
    }
    
    // MARK: - 配置Cell
    private func configItem() {
//        for _ in 0..<9 {
//            let model = MYGCommunityRecommendCellModel(title: "心外科",
//                                                       icon: "https://img2.baidu.com/it/u=3447853342,1372997766&fm=253&fmt=auto&app=120&f=JPEG?w=1026&h=646")
//            contents.append(model)
//        }
//        
//        recommentView.reload(with: contents)
    }
    
    private func loadData() {
        MYGLoading.show(self.view)
        MYGCommunityManager.shareManager.getAllCommunities { models in
            MYGLoading.hide(self.view)
            let cellModels = models.map { model in
                MYGCommunityRecommendCellModel(id:String(model.id), title: model.name, icon: model.img)
            }
            self.recommentView.reload(with: cellModels)
        }
    }
    
    
    // MARK: - lazy load
    private lazy var recommnedTitleLabel: UILabel = {
        let label = UILabel(text: "推荐社群")
        label.font = .medium(25)
        label.textColor = .rgba(47, 47, 47)
        return label
    }()
    
    private lazy var recommentSubtitleLabel: UILabel = {
        let label = UILabel(text: "随堂实操，随学随做更好掌握！")
        label.font = .regular(16)
        label.textColor = .rgba(115, 115, 115)
        return label
    }()
    
    private lazy var backgroundImageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "Community/recommend_bg"))
        return imageView
    }()
    
    private lazy var recommentView: MYGCommunityRecommendView = {
        let view = MYGCommunityRecommendView(frame: .zero)
        view.reloadButonTitle = { [self] in
            let selectedIds = recommentView.cellModels.filter({ $0.isSelected }).map({ $0.id })
            followButton.setTitle("关注更多社群(\(selectedIds.count))", for: .normal)
        }
        return view
    }()
    
    private lazy var followButton: UIButton = {
        let button = UIButton(type: .custom)
        //button.backgroundColor = .rgba(162, 146, 254)
        button.setTitle("关注更多社群", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = .medium(15)
        button.layerCornerRadius = 20
        button.addCAGradientLayerColor(colors: [UIColor.init(hexString: "#97B3FF").cgColor,
                                                 UIColor.init(hexString: "#4975EC").cgColor],
                                        startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint.init(x: 1, y: 0))
        button.addTarget(self, action: #selector(followAction), for: .touchUpInside)
        return button
    }()
}


extension MYGCommunityRecommendController {
    
    
    
    
    @objc func followAction() {
        let selectedIds = recommentView.cellModels.filter({ $0.isSelected }).map({ $0.id })
        
        if selectedIds.count == 0 {
            MYGCommunityManager.shareManager.isFirstEnterCommunity = true
            let vc = MYGAnswerViewViewController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
            return
        }
        
        MYGLoading.show(self.view)
        let ids = selectedIds.joined(separator: ",")
        MYGNetwork<MYGCommunityApi, MYGEmptyModel>.request(target: .doctor_bind_communities(communities_ids: ids)) { _ in
            MYGCommunityManager.shareManager.isFirstEnterCommunity = true
            MYGLoading.hide(self.view)
            let vc = MYGAnswerViewViewController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
        } failed: { _, error in
            MYGLoading.hide(self.view)
            MMYGHUD.showToast(text: error)
        }
        
        
//        
//        MYGLoading.show(self.view)
//        let group = DispatchGroup()
//        for id in selectedIds {
//            group.enter()
//            MYGNetwork<MYGCommunityApi, MYGEmptyModel>.request(target: .collect(id: id)) { _ in
//                group.leave()
//            } failed: { _, _ in
//                group.leave()
//            }
//        }
//        
//        
//        group.notify(queue: DispatchQueue.main) {[weak self] in
//            MYGCommunityManager.shareManager.isFirstEnterCommunity = true
//            MYGLoading.hide(self?.view)
//            let vc = MYGAnswerViewViewController()
//            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
//        }
    }
}
